﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using eTerm.MsSql.DbProvider;
using eTerm.Platform.Common;
using System.Text.RegularExpressions;
using eTerm.NetSocket.Utils;

namespace eTerm.Platform.Web.Order.UserControls
{
    public partial class DetailMode : BaseEntityUserControl<PnrRequire>
    {

        /// <summary>
        /// 初始化用户控件
        /// </summary>
        public override void InitControl()
        {
            PnrRequire mode = new PnrRequire()
            {
                LSTFK_PNR_PASS_REFERENCE_PNR_REQU = new List<PnrPassenger>()
                {
                    new PnrPassenger(){ IdentityType = (int)PNRPassengerIdentityType.身份证, PassengerType = (int)PNRPassengerType.AD}
                },
                LSTFK_PNR_SEGM_REFERENCE_PNR_REQU = new List<PnrSegment>() { 
                    new PnrSegment(){ }
                }
            };

            long pK = !string.IsNullOrEmpty(EntityIdentity) ? long.Parse(EntityIdentity) : 0;
            if (IsReadOnly)
            {
                mode.LSTFK_PNR_PASS_REFERENCE_PNR_REQU.Clear();
                mode.LSTFK_PNR_SEGM_REFERENCE_PNR_REQU.Clear();
            }
            if (pK != 0)
            {
                PnrSegment.All().Where(l => l.RequireId == pK).ToList().ForEach(l =>
                {
                    mode.LSTFK_PNR_SEGM_REFERENCE_PNR_REQU.Add(l);
                });
                PnrPassenger.All().Where(l => l.RequireId == pK).ToList().ForEach(l =>
                {
                    mode.LSTFK_PNR_PASS_REFERENCE_PNR_REQU.Add(l);
                });
            }

            rptSegment.DataSource = mode.LSTFK_PNR_SEGM_REFERENCE_PNR_REQU.OrderBy(l=>l.DepartureDate);
            rptSegment.DataBind();

            rptPassenger.DataSource = mode.LSTFK_PNR_PASS_REFERENCE_PNR_REQU;
            rptPassenger.DataBind();
        }

        protected override void SaveEntity(PnrRequire model)
        {
            model.Save();
        }

        protected override PnrRequire GetEntityFromControl()
        {
            PnrRequire model = string.IsNullOrEmpty(EntityIdentity) ? new PnrRequire() { RecordDate = DateTime.Now, UserId = UID, StatusId = 1, RequireCode = StringUtil.GenUniqueString() } : PnrRequire.FirstOrDefault(l => l.Id == long.Parse(EntityIdentity));
            return model;
        }

        protected void rptPassenger_OnItemDataBound(object sender, RepeaterItemEventArgs e) {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
                PnrPassenger model = e.Item.DataItem as PnrPassenger;
                TextBox tbName = e.Item.FindControl(@"tbName") as TextBox;
                TextBox tbIdentityNo = e.Item.FindControl(@"tbIdentityNo") as TextBox;
                TextBox tbBirthday = e.Item.FindControl(@"tbBirthday") as TextBox;
                DropDownList dlPassengerType = e.Item.FindControl(@"dlPassengerType") as DropDownList;
                DropDownList dlIdentityType = e.Item.FindControl(@"dlIdentityType") as DropDownList;

                LinkButton btnDelete = e.Item.FindControl(@"btnDelete") as LinkButton;
                LinkButton btnSave = e.Item.FindControl(@"btnSave") as LinkButton;

                btnDelete.Visible /*= btnSelect.Visible*/ = btnSave.Visible = !string.IsNullOrEmpty(EntityIdentity);
                tbName.Text = model.PassengerName;
                tbIdentityNo.Text = model.IdentityNo;
                tbBirthday.Text = model.Birthday.HasValue ? model.Birthday.Value.ToString(@"yyyy-MM-dd") : string.Empty;


                btnSave.CommandArgument = model.Id.ToString();
                btnDelete.CommandArgument = model.Id.ToString();


                Enum.GetValues(typeof(PNRPassengerType)).Cast<int>().ToList().ForEach(l =>
                {
                    ListItem item = new ListItem() { Text = EnumHelper.GetDescription((PNRPassengerType)l),Value = l.ToString(), Selected = l==model.IdentityType  };
                    dlPassengerType.Items.Add(item);
                });


                Enum.GetValues(typeof(PNRPassengerIdentityType)).Cast<int>().ToList().ForEach(l =>
                {
                    ListItem item = new ListItem() { Text = EnumHelper.GetDescription((PNRPassengerIdentityType)l), Value = l.ToString(), Selected = l == model.PassengerType };
                    dlIdentityType.Items.Add(item);
                });

                tbName.ToolTip = string.Format(@"请先确认乘客姓名受eTerm字库支持，<br />否则系统将无法完成自动订座。", @"");


                BaseRegisterStartupScript<UserControl>(this, tbName.ClientID, string.Format(@"$(""#{0}"").poshytip({{
                 showTimeout: 300,
                 allowTipHover: true,
                 fade: true,
                 className:'tip-darkgray',
                 slide: true
             }});  
", tbName.ClientID), true);


                BaseRegisterStartupScript<UserControl>(this, tbBirthday.ClientID, string.Format(@"$('#{0}').datebox();  
", tbBirthday.ClientID), true);

                BaseRegisterStartupScript<UserControl>(this, dlPassengerType.ClientID, string.Format(@"$('#{0}').combobox();  
", dlPassengerType.ClientID), true);

                BaseRegisterStartupScript<UserControl>(this, dlIdentityType.ClientID, string.Format(@"$('#{0}').combobox();  
", dlIdentityType.ClientID), true);


                BaseRegisterStartupScript<UserControl>(this, btnDelete.ClientID, string.Format(@"$('#{0}').linkbutton({{   
    iconCls: 'icon-delete'  
}});  
", btnDelete.ClientID), true);

                BaseRegisterStartupScript<UserControl>(this, btnSave.ClientID, string.Format(@"$('#{0}').linkbutton({{   
    iconCls: 'icon-page_save'  
}});  
", btnSave.ClientID), true);


            }
        }

        protected void rptSegment_OnItemCommand(object sender, RepeaterCommandEventArgs e) {
            if (e.CommandName == @"Save") {
                SaveSegment(e.CommandArgument.ToString(),e.Item);
            } else if (e.CommandName == @"Delete") {
                DeleteSegment(e.CommandArgument.ToString());   
            }
            InitControl();
        }



        protected void rptPassenger_OnItemCommand(object sender, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == @"Save")
            {
                SavePassenger(e.CommandArgument.ToString(), e.Item);
            }
            else if (e.CommandName == @"Delete")
            {
                DeletePassenger(e.CommandArgument.ToString());
            }
            InitControl();
        }

        private void DeletePassenger(string Key) {
            long KeyValue = long.Parse(Key);

            new PnrPassenger().Delete(l => l.Id == KeyValue);
        }

        private void SavePassenger(string Key, RepeaterItem e) {
            long KeyValue = long.Parse(Key);
            PnrPassenger model = PnrPassenger.FirstOrDefault(l => l.Id == KeyValue) ?? new PnrPassenger();

            TextBox tbName = e.FindControl(@"tbName") as TextBox;
            TextBox tbIdentityNo = e.FindControl(@"tbIdentityNo") as TextBox;
            TextBox tbBirthday = e.FindControl(@"tbBirthday") as TextBox;

            DropDownList dlPassengerType = e.FindControl(@"dlPassengerType") as DropDownList;
            DropDownList dlIdentityType = e.FindControl(@"dlIdentityType") as DropDownList;

            model.RequireId = long.Parse(EntityIdentity);
            model.PassengerName = tbName.Text.Trim();
            model.PassengerType = int.Parse(dlPassengerType.SelectedValue);
            model.IdentityType = int.Parse(dlIdentityType.SelectedValue);
            model.IdentityNo = tbIdentityNo.Text.Trim();
            model.Birthday = string.IsNullOrEmpty(tbBirthday.Text.Trim()) ? null : DateTime.Parse(tbBirthday.Text.Trim()) as DateTime?;

            model.Save();

            PnrRequire pnrModel = PnrRequire.FirstOrDefault(l => l.Id == model.RequireId);
            pnrModel.StatusId = (int)PNRRequireStatus.PENDDING;
            pnrModel.Save();
        }

        private void SaveSegment(string Key,RepeaterItem e) {
            long KeyValue = long.Parse(Key);
            PnrSegment model = PnrSegment.FirstOrDefault(l => l.Id == KeyValue)??new PnrSegment();

            TextBox tbDeparture = e.FindControl(@"tbDeparture") as TextBox;
            TextBox tbArrival = e.FindControl(@"tbArrival") as TextBox;
            TextBox tbFlightNo = e.FindControl(@"tbFlightNo") as TextBox;
            TextBox tbFlightDate = e.FindControl(@"tbFlightDate") as TextBox;
            TextBox tbCabinCode = e.FindControl(@"tbCabinCode") as TextBox;

            TextBox tbStartRangeTime = e.FindControl(@"tbStartRangeTime") as TextBox;
            TextBox tbEndRangeTime = e.FindControl(@"tbEndRangeTime") as TextBox;


            model.StartRangeTime =tbStartRangeTime.Text.Trim().Replace(":",string.Empty);
            model.EndRangeTime = tbEndRangeTime.Text.Trim().Replace(":", string.Empty);
            model.RequireId = long.Parse(EntityIdentity);
            model.Arrival = tbArrival.Text.Trim();
            model.Departure = tbDeparture.Text.Trim();
            model.DepartureDate = DateTime.Parse(tbFlightDate.Text);
            model.FlightNo = tbFlightNo.Text.Trim();
            model.CabinCode =string.IsNullOrEmpty(tbFlightNo.Text.Trim())?Regex.Replace( tbCabinCode.Text.Trim(),@"\,+",@",", RegexOptions.Multiline| RegexOptions.IgnoreCase)+ (tbCabinCode.Text.Trim().EndsWith( ";")?string.Empty:";") : tbCabinCode.Text.Trim();
            model.IsInvalid = false;
            model.Save();

            PnrRequire pnrModel = PnrRequire.FirstOrDefault(l => l.Id == model.RequireId);
            pnrModel.StatusId = (int)PNRRequireStatus.PENDDING;
            pnrModel.Save();

        }

        private void DeleteSegment(string Key) {
            long KeyValue = long.Parse(Key);

            new PnrRequireCode().Delete(l => l.SegmentId == KeyValue);
            new PnrSegment().Delete(l => l.Id == KeyValue);
            PnrRequire model =  PnrRequire.FirstOrDefault(l => l.Id == KeyValue);
            model.StatusId = (int)PNRRequireStatus.PENDDING;
            model.Save();


        }


        protected void rptSegment_OnItemDataBound(object sender, RepeaterItemEventArgs e) {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
                PnrSegment model = e.Item.DataItem as PnrSegment;
                TextBox tbDeparture = e.Item.FindControl(@"tbDeparture") as TextBox;
                TextBox tbArrival = e.Item.FindControl(@"tbArrival") as TextBox;
                TextBox tbFlightNo = e.Item.FindControl(@"tbFlightNo") as TextBox;
                TextBox tbFlightDate = e.Item.FindControl(@"tbFlightDate") as TextBox;
                TextBox tbCabinCode = e.Item.FindControl(@"tbCabinCode") as TextBox;
                TextBox tbStartRangeTime = e.Item.FindControl(@"tbStartRangeTime") as TextBox;
                TextBox tbEndRangeTime = e.Item.FindControl(@"tbEndRangeTime") as TextBox;
                LinkButton btnDelete = e.Item.FindControl(@"btnDelete") as LinkButton;
                LinkButton btnSave = e.Item.FindControl(@"btnSave") as LinkButton;
                //LinkButton btnSelect = e.Item.FindControl(@"btnSelect") as LinkButton;
                btnDelete.Visible /*= btnSelect.Visible*/ = btnSave.Visible = !string.IsNullOrEmpty(EntityIdentity);
                tbDeparture.Text = (model.Departure ?? string.Empty).Trim();
                tbArrival.Text = (model.Arrival??string.Empty).Trim();
                tbFlightNo.Text = (model.FlightNo??string.Empty).Trim();
                tbFlightDate.Text = (model.DepartureDate ?? DateTime.Now.AddDays(1)).ToString(@"yyyy-MM-dd");
                tbCabinCode.Text = model.CabinCode ?? string.Empty;
                btnSave.CommandArgument = model.Id.ToString();
                btnDelete.CommandArgument = model.Id.ToString();

                //tbDeparture.CausesValidation = tbArrival.CausesValidation = tbCabinCode.CausesValidation = !string.IsNullOrEmpty(EntityIdentity);

                tbFlightNo.ToolTip = string.Format(@"格式要求如下：<br />一、MU5206、CA989、9C3849 <br />二、保留空值[说明不限定航班]。", @"");

                tbCabinCode.ToolTip = string.Format(@"格式要求如下：<br />一、当航班号为空值时：MU:Y,K,X,M1;CA:H,X,J,B1 <br />二、当航班号不空时：H,X,J,B1", @"");

                BaseRegisterStartupScript<UserControl>(this, tbFlightDate.ClientID, string.Format(@"$('#{0}').datebox();  
", tbFlightDate.ClientID), true);

//                BaseRegisterStartupScript<UserControl>(this, btnSelect.ClientID, string.Format(@"$('#{0}').linkbutton({{   
//    iconCls: 'icon-search'  
//}});  
//", btnSelect.ClientID), true);

                BaseRegisterStartupScript<UserControl>(this, btnDelete.ClientID, string.Format(@"$('#{0}').linkbutton({{   
    iconCls: 'icon-delete'  
}});  
", btnDelete.ClientID), true);

                BaseRegisterStartupScript<UserControl>(this, btnSave.ClientID, string.Format(@"$('#{0}').linkbutton({{   
    iconCls: 'icon-page_save'  
}});  
", btnSave.ClientID), true);


                BaseRegisterStartupScript<UserControl>(this, tbFlightNo.ClientID, string.Format(@"$(""#{0}"").poshytip({{
                 showTimeout: 300,
                 allowTipHover: true,
                 fade: true,
                 className:'tip-darkgray',
                 slide: true
             }});  
", tbFlightNo.ClientID), true);


                BaseRegisterStartupScript<UserControl>(this, tbCabinCode.ClientID, string.Format(@"$(""#{0}"").poshytip({{
                 showTimeout: 300,
                 allowTipHover: true,
                 fade: true,
                 className:'tip-darkgray',
                 slide: true
             }});  
", tbCabinCode.ClientID), true);


                BaseRegisterStartupScript<UserControl>(this, tbStartRangeTime.ClientID, string.Format(@"$(""#{0}"").timespinner({{   
    min: '00:00',  
    max: '24:00', 
    showSeconds: false  
}});   
", tbStartRangeTime.ClientID), true);

                BaseRegisterStartupScript<UserControl>(this, tbEndRangeTime.ClientID, string.Format(@"$(""#{0}"").timespinner({{   
    min: '00:00',   
    max: '23:59', 
    showSeconds: false  
}});   
", tbEndRangeTime.ClientID), true);

                BaseRegisterStartupScript<UserControl>(this, tbEndRangeTime.ClientID + "1", string.Format(@"$('#{0}').timespinner('setValue', '{1}');", tbEndRangeTime.ClientID, string.IsNullOrEmpty(model.EndRangeTime) ? string.Empty : model.EndRangeTime.Insert(2, ":")), true);
                BaseRegisterStartupScript<UserControl>(this, tbStartRangeTime.ClientID + "1", string.Format(@"$('#{0}').timespinner('setValue', '{1}');", tbStartRangeTime.ClientID, string.IsNullOrEmpty(model.StartRangeTime) ? string.Empty : model.StartRangeTime.Insert(2, ":")), true);


                //tbFlightNo.Attributes.Add(@"onfocus", string.Format(@"javascript:alert('');"));

            }
        }
    }
}